//
//  UserCenterNew.m
//  cutter
//
//  Created by mac on 16/1/5.
//  Copyright © 2016年 e360. All rights reserved.
//

#import "UserCenterNew.h"
@interface UserCenterNew ()
@property(nonatomic, strong) NSMutableDictionary *group;
@property(nonatomic, strong) NSMutableDictionary *value;
@property(nonatomic, strong) NSMutableArray *data;
@end
@implementation UserCenterNew
-(void)viewDidLoad{
    [super viewDidLoad];
    if (self.client) {
        [self setGroup:[self.client objectForKey:@"group"]];
        [self.groupView setText:[AppData objToString:[self.group objectForKey:@"groupname"] lable:nil]];
        [self.nameView setText:[AppData objToString:[self.client objectForKey:@"truename"] lable:nil]];
        [self.mobileView setText:[AppData objToString:[self.client objectForKey:@"mobile"] lable:nil]];
        [self.emailView setText:[AppData objToString:[self.client objectForKey:@"email"] lable:nil]];
        [self.addressView setText:[AppData objToString:[self.client objectForKey:@"address"] lable:nil]];
    }else{
        [self setClient:[NSMutableDictionary dictionary]];
        [self.client setValue:[NSString uuid] forKey:@"uuid"];
    }
    [self updataComponent:0];
}
-(NSMutableDictionary *)value{
    if (_value == nil) {
        [self setValue:[NSMutableDictionary dictionary]];
    }
    return _value;
}
-(NSMutableArray *)data{
    if (_data == nil) {
        [self setData:[NSMutableArray array]];
        [self.data addObject:[NSMutableArray array]];
        [self.data addObject:[NSMutableArray array]];
        [self.data addObject:[NSMutableArray array]];
    }
    return _data;
}
//
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return [self.data count];
}
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    NSArray *item = [self.data objectAtIndex:component];
    return [item count];
}
-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSArray *items = [self.data objectAtIndex:component];
    if (row < items.count) {
        NSDictionary *item = [items objectAtIndex:row];
        return [item objectForKey:@"areaname"];
    }
    return @"";
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSString *key = [NSString stringWithFormat:@"%ld",(long)component];
    [self.value setValue:nil forKey:key];
    if (component < [self.data count]) {
        NSArray *items = [self.data objectAtIndex:component];
        if (row < items.count) {
            NSDictionary *item = [items objectAtIndex:row];
            [self.value setValue:item forKey:key];
        }
    }
    [self updataComponent:component + 1];
    //
    NSArray *keys = [self.value.allKeys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSInteger a = [obj1 integerValue];
        NSInteger b = [obj1 integerValue];
        if (a < b) {
            return NSOrderedDescending;
        }
        if (a > b) {
            return NSOrderedAscending;
        }
        return NSOrderedSame;
    }];
    NSMutableArray *temp = [NSMutableArray array];
    for (id key in keys) {
        [temp addObject:[[self.value objectForKey:key] objectForKey:@"areaname"]];
    }
    [self.areaView setText:[temp componentsJoinedByString:@"-"]];
}
-(void)updataComponent:(NSInteger)component{
    if (component < [self.data count]) {
        NSMutableArray *item = [self.data objectAtIndex:component];
        [item removeAllObjects];
        //
        id pid = @"0";
        if (component > 0) {
            NSString *key = [NSString stringWithFormat:@"%ld",(long)component - 1];
            pid = [[self.value objectForKey:key] objectForKey:@"id"];
        }
        if (pid != nil) {
            NSArray *temp = [AppData areaList:pid];
            [item addObjectsFromArray:temp];
        }
        [self.pickerView reloadComponent:component];
        //
        NSInteger row = [self rowAtData:item component:component];
        [self.pickerView selectRow:row inComponent:component animated:NO];
        [self pickerView:self.pickerView didSelectRow:row inComponent:component];
    }
}
-(NSInteger)rowAtData:(NSArray*)data component:(NSInteger)component{
    NSString *aid = nil;
    switch (component) {
        case 2:
            aid = [self.client objectForKey:@"area"];
            break;
        case 1:
            aid = [self.client objectForKey:@"city"];
            break;
        default:
            aid = [self.client objectForKey:@"province"];
            break;
    }
    if (aid) {
        for (uint i=0; i<data.count; i++) {
            id temp = [data objectAtIndex:i];
            if ([[temp objectForKey:@"id"] isEqual:aid]) {
                return i;
            }
        }
    }
    return 0;
}
//
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.destinationViewController isKindOfClass:UserCenterGroup.class]) {
        UserCenterGroup *group = segue.destinationViewController;
        //
        __weak UserCenterNew *this = self;
        [group setOnSelected:^(id target, id result){
            if (result) {
                [this setGroup:result];
                [this.groupView setText:[result objectForKey:@"groupname"]];
                [this.navigationController popViewControllerAnimated:YES];
            }else{
                [this closeTouch:nil];
            }
        }];
    }
}
//
- (IBAction)doneTouch:(id)sender {
    if (self.group) {
        if ([self.nameView.text length] == 0 || [self.nameView.text rangeOfString:@"\\w{2,12}" options:NSRegularExpressionSearch].location == NSNotFound) {
            [UIAlertController show:nil message:@"客户名为空或有误!" buttons:nil handler:nil];
            return;
        }
        if ([self.mobileView.text length] == 0 || [self.mobileView.text rangeOfString:@"^1[3|4|5|7|8]\\d{9}$" options:NSRegularExpressionSearch].location == NSNotFound) {
            [UIAlertController show:nil message:@"手机号为空或有误!" buttons:nil handler:nil];
            return;
        }
        if ([self.emailView.text length] > 0 && [self.emailView.text rangeOfString:@"^\\w+@\\w+(\\.\\w+)+$" options:NSRegularExpressionSearch].location == NSNotFound) {
            [UIAlertController show:nil message:@"邮箱有误!" buttons:nil handler:nil];
            return;
        }
        //
        [self.client setValue:[[self.value objectForKey:@"0"] objectForKey:@"areaname"] forKey:@"provincename"];
        [self.client setValue:[[self.value objectForKey:@"1"] objectForKey:@"areaname"] forKey:@"cityname"];
        [self.client setValue:[[self.value objectForKey:@"2"] objectForKey:@"areaname"] forKey:@"areaname"];
        [self.client setValue:[[self.value objectForKey:@"0"] objectForKey:@"id"] forKey:@"province"];
        [self.client setValue:[[self.value objectForKey:@"1"] objectForKey:@"id"] forKey:@"city"];
        [self.client setValue:[[self.value objectForKey:@"2"] objectForKey:@"id"] forKey:@"area"];
        //
        [self.client setValue:[self.group objectForKey:@"uuid"] forKey:@"groupid"];
        [self.client setValue:self.addressView.text forKey:@"address"];
        [self.client setValue:self.nameView.text forKey:@"truename"];
        [self.client setValue:self.mobileView.text forKey:@"mobile"];
        [self.client setValue:self.emailView.text forKey:@"email"];
        //
        id user = [TMGlobal valueForKey:@"user"];
        id parentid = [self.client objectForKey:@"parentid"];
        if (user && parentid == nil) {
            [self.client setValue:[user objectForKey:@"id"] forKey:@"parentid"];
        }
        //
        __weak UserCenterNew *this = self;
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [AppData userEditClient:this.client];
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUDForView:this.view animated:YES];
                if (this.onSelected) {
                    this.onSelected(this, this.client);
                }
            });
        });
    }else{
        [UIAlertController show:nil message:@"请选择分组!" buttons:nil handler:nil];
    }
}
- (IBAction)closeTouch:(id)sender {
    if (self.onSelected) {
        self.onSelected(self, nil);
    }
}
@end
